﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Globalization;
using System.Reflection;
using System.Xml;
using System.Collections.Generic;

namespace Biciq.Silverlight.UI.Clases
{
    public static class Utiles
    {
        public static string ObtenerAppSetting(string appSettingKey, string defaultValue)
        {
            string appSettingValue = ConfigurationManager.AppSettings[appSettingKey];

            if (appSettingValue == null)
            {
                if (defaultValue == null)
                    throw new Exception(String.Format(CultureInfo.InvariantCulture, "Clave de aplicación no registrada", appSettingKey));
                return defaultValue;
            }

            return appSettingValue;
        }

        
    }

    /// <summary>
    ///  Clase que simula ConfigurationManager para leer settings de aplicacion
    ///  </summary>
    public static class ConfigurationManager
    {
        public static AppSettings AppSettings
        {
            get;
            private set;
        }

        static ConfigurationManager()
        {
            AppSettings appSettings = new AppSettings();

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.XmlResolver = new XmlXapResolver();
            XmlReader reader = XmlReader.Create("ServiceReferences.ClientConfig");
            reader.MoveToContent();
            reader.ReadToDescendant("appSettings");
            reader.ReadToDescendant("add");
            do
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "add")
                {
                    appSettings.Add(new KeyValuePair<string, string>(reader.GetAttribute("key"), reader.GetAttribute("value")));
                }
                else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "appSettings")
                {
                    break;
                }
            } while (reader.Read());
            AppSettings = appSettings;
        }

    }

    /// <summary>
    ///  Configuraciones de aplicacion
    ///  </summary>
    public class AppSettings
    {
        public string this[string key]
        {
            get
            {
                if (_settings.ContainsKey(key)) return _settings[key];
                return null;
            }
        }

        private IDictionary<string, string> _settings;

        public AppSettings()
        {
            _settings = new Dictionary<string, string>();
        }

        public void Add(KeyValuePair<string, string> settings)
        {
            _settings.Add(settings);
        }
    }

   

}
    
